package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.domain.LEmployee;
import com.ruoyi.system.domain.LRegion;
import com.ruoyi.system.service.*;
import com.ruoyi.system.template.LGuestTemplate;
import com.ruoyi.system.vo.LGuestParam;
import com.ruoyi.system.vo.LGuestVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.LGuestMapper;
import com.ruoyi.system.domain.LGuest;

import javax.validation.Validator;

import static com.ruoyi.common.utils.SecurityUtils.getUserId;

/**
 * 客户Service业务层处理
 *
 * @author zyb
 * @date 2022-01-02
 */
@Service
public class LGuestServiceImpl extends ServiceImpl<LGuestMapper, LGuest> implements ILGuestService {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ILRegionService regionService;
    @Autowired
    private ILEmployeeService employeeService;
    @Autowired
    protected Validator validator;

    /**
     * 查询客户
     *
     * @param gid 客户主键
     * @return 客户
     */
    @Override
    public LGuest selectLGuestByGid(Long gid) {
        return baseMapper.selectLGuestByGid(gid);
    }

    /**
     * 查询客户列表
     *
     * @param lGuest 客户
     * @return 客户
     */
    @Override
    public List<LGuest> selectLGuestList(LGuestVo lGuest) {
        return baseMapper.selectLGuestList(lGuest);
    }

    /**
     * 新增客户
     *
     * @param lGuest 客户
     * @return 结果
     */
    @Override
    public int insertLGuest(LGuest lGuest) {
        lGuest.setCreateBy(String.valueOf(getUserId()));
        lGuest.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insertLGuest(lGuest);
    }

    /**
     * 修改客户
     *
     * @param lGuest 客户
     * @return 结果
     */
    @Override
    public int updateLGuest(LGuest lGuest) {
        lGuest.setUpdateBy(String.valueOf(getUserId()));
        lGuest.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateLGuest(lGuest);
    }

    /**
     * 批量删除客户
     *
     * @param gids 需要删除的客户主键
     * @return 结果
     */
    @Override
    public int deleteLGuestByGids(Long[] gids) {
        return baseMapper.deleteLGuestByGids(gids);
    }

    /**
     * 删除客户信息
     *
     * @param gid 客户主键
     * @return 结果
     */
    @Override
    public int deleteLGuestByGid(Long gid) {
        return baseMapper.deleteLGuestByGid(gid);
    }

    @Override
    public List<SysUser> bindUserList() {
        return baseMapper.bindUserList();
    }

    @Override
    public Map<String, Object> bindUser(LGuest lGuest) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 1);
        map.put("msg", lGuest.getName() + "，绑定成功");
        if (lGuest.getGid() == null) {
            map.put("code", -1);
            map.put("msg", "绑定失败，系统错误");
            return map;
        }
        if (lGuest.getUserid() == null) {
            baseMapper.unbindUserList(lGuest.getGid());
            map.put("code", 1);
            map.put("msg", lGuest.getName() + "，解绑成功");
            return map;
        }
        LGuestVo param = new LGuestVo();
        param.setUserid(lGuest.getUserid());
        List<LGuest> LGuestList = baseMapper.selectLGuestList(param);
        if (LGuestList.size() > 0) {
            map.put("code", -1);
            map.put("msg", lGuest.getName() + "，绑定失败，用户已经绑定，客户信息，请重新选择");
            return map;
        }
        param.setGid(lGuest.getGid());
        int i = baseMapper.updateLGuest(param);
        if (i == 0) {
            map.put("code", -2);
            map.put("msg", lGuest.getName() + "，绑定失败，系统错误");
            return map;
        }
        return map;
    }

    @Override
    public Map<String, Object> generateUser(Long gid) {
        Map<String, Object> map = new HashMap<>();
        LGuest lGuest = baseMapper.selectLGuestByGid(gid);
        SysUser u = userService.selectUserByUserName(lGuest.getPhone());
        if (StringUtils.isNull(u)) {
            SysUser user = new SysUser();
            user.setUserName(lGuest.getPhone());
            if (StringUtils.isNotNull(lGuest.getName())) {
                user.setNickName(lGuest.getName());
            } else if (StringUtils.isNotNull(lGuest.getContractor())) {
                user.setNickName(lGuest.getContractor());
            } else {
                map.put("code", -1);
                map.put("msg", lGuest.getPhone() + "，生成用户失败，名称为空");
                return map;
            }
            String password = configService.selectConfigByKey("sys.user.initPassword");
            user.setPassword(SecurityUtils.encryptPassword(password));
            user.setType("2");
            String deptId = configService.selectConfigByKey("customer.deptId");
            user.setDeptId(Long.parseLong(deptId));
            user.setPhonenumber(lGuest.getPhone());
            user.setRemark("系统生成用户");
            try {
                userService.insertUser(user);
                lGuest.setUserid(user.getUserId());
                return this.bindUser(lGuest);

            } catch (Exception e) {
                map.put("code", -1);
                map.put("msg", lGuest.getPhone() + "生成用户失败，" + e.getMessage());
            }

        } else {
            map.put("code", -1);
            map.put("msg", "生成用户失败，用户名称已经存在,\"" + lGuest.getPhone() + "\"");

        }
        return map;
    }

    @Override
    public List<Map<String, Object>> batchGenerateUser(Long[] gids) {
        List<Map<String, Object>> List = new ArrayList<>();
        for (Long gid : gids) {
            List.add(this.generateUser(gid));
        }
        return List;
    }

    @Override
    public List<Map<String, Object>> batchGenerateUserAll() {
        List<Map<String, Object>> List = new ArrayList<>();
        List<LGuest> lGuestList = baseMapper.selectLGuestNoUserIdList();
        for (LGuest guest : lGuestList) {
            List.add(this.generateUser(guest.getGid()));
        }
        return List;
    }

    @Override
    public LGuestVo selectByUserId(Long userId) {
        return baseMapper.selectByUserId(userId);
    }

    @Override
    public String importGuest(List<LGuestTemplate> guestList, Boolean isUpdateSupport) {
        if (StringUtils.isNull(guestList) || guestList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (LGuestTemplate template : guestList) {
            LGuest lGuest = new LGuest();
            BeanUtils.copyProperties(template, lGuest);
            LRegion region = new LRegion();
            region.setVillage(template.getArea());
            //区域
            Long areaId = regionService.getId(region);
            if (areaId > 0)lGuest.setAreaid(areaId);
            //业务员
            LEmployee employee = new LEmployee();
            employee.setName(template.getEmp());
            employee.setIssale(1);
            Integer emi=employeeService.getId(employee);
            if (emi > 0)lGuest.setEmpid(Long.parseLong(String.valueOf(emi)));
            //司机
            LEmployee driver = new LEmployee();
            driver.setName(template.getEmp());
            driver.setIsdriver(1);
            Integer driverId=employeeService.getId(driver);
            if (driverId > 0)lGuest.setDriverid(Long.parseLong(String.valueOf(driverId)));

            try {
                // 验证是否存在这个用户
                LGuest g = this.baseMapper.selectOne(new LambdaQueryWrapper<LGuest>().eq(LGuest::getCode, lGuest.getCode()));
                if (StringUtils.isNull(g)) {
                    BeanValidators.validateWithException(validator, lGuest);
                    this.insertLGuest(lGuest);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、客户 " + lGuest.getName() +","+ lGuest.getPhone()+","+lGuest.getCode()+ " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, lGuest);
                    lGuest.setGid(g.getGid());
                    this.updateLGuest(lGuest);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、客户 " + lGuest.getName()+","+ lGuest.getPhone()+","+lGuest.getCode() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、客户 " + lGuest.getName()+","+ lGuest.getPhone()+","+lGuest.getCode() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、客户 " + lGuest.getName()+","+ lGuest.getPhone()+","+lGuest.getCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public Long getId(LGuest guest) {

        List<LGuest> guestList= this.baseMapper.selectList(new LambdaQueryWrapper<LGuest>(guest));
        if(guestList.size()>0)return guestList.get(0).getGid();
        return 0L;
    }

    @Override
    public List<LGuestVo> reportGuest(LGuestParam guestParam) {
        return this.baseMapper.reportGuest(guestParam);
    }


}
